package com.nx.platform.es.bean.modle.score;

import com.google.common.collect.ImmutableMap;
import org.apache.commons.collections4.MapUtils;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder.FilterFunctionBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.index.query.functionscore.ScriptScoreFunctionBuilder;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptType;

import java.util.Map;

/**
 * @author
 * @since 2016年10月15日
 */
public class NativeScriptFunctionHandler implements ScoreFunctionFieldHandler {

    @Override
    public FilterFunctionBuilder handle(ImmutableMap<String, ?> fieldConfig, Map<String, Object> params) {
        String scriptName = MapUtils.getString(fieldConfig, "scriptName");
        float weight = MapUtils.getFloatValue(fieldConfig, "weight", 0f);
        Script script = new Script(ScriptType.INLINE, "native", scriptName, params);
        ScriptScoreFunctionBuilder function = ScoreFunctionBuilders.scriptFunction(script);
        if (weight > 0) {
            function.setWeight(weight);
        }
        return new FilterFunctionBuilder(function);
    }

}
